package dto

import (
	"encoding/json"
	"server-admin-api/global"
	"server-admin-api/models"
	"server-admin-api/views"
)

type GroupDto struct {}

func NewGroupDto() *GroupDto {
	return &GroupDto{}
}


func (g *GroupDto) Count() (int64, error) {
	var data int64
	if err := global.DB.Model(&models.Group{}).Count(&data).Error; err != nil {
		return 0, err
	}
	return data, nil
}

func (g *GroupDto) List(page int, size int, title string) ([]models.Group, error) {
	var data []models.Group
	tx := global.DB.
		Order("up_time desc").
		Limit(size).
		Offset((page - 1) * size)
	if title != "" {
		tx = tx.Where("title like %?%", title)
	}
	if err := tx.Find(&data).Error; err != nil {
		return nil, err
	}
	return data, nil
}

func (g *GroupDto) Insert(data models.Group) error {
	return global.DB.Create(&data).Error
}


func (g *GroupDto) Update(id uint, data views.GroupCreate) error {
	var m map[string]interface{}
	b, _ := json.Marshal(&data)
	_ = json.Unmarshal(b, &m)
	return global.DB.Model(&models.Group{}).Where("id = ?", id).Updates(m).Error
}


func (g *GroupDto) DeleteOne(id uint) error {
	return global.DB.Delete(&models.Group{}, id).Error
}